from selenium import webdriver
from selenium.webdriver.common.action_chains import ActionChains
from selenium.webdriver.support.wait import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
import time
import logging
import socket
import pymysql
import demjson
import pathlib
import sqlite3
logging.basicConfig(level=logging.INFO,format='%(asctime)s -%(levelname)s -%(process)d -%(module)s -%(funcName)s -%(message)s')
root=pathlib.Path(__file__).parent
db=sqlite3.connect(str(root/"2_class.db"))
cur = db.cursor()
s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
s.connect(("8.8.8.8", 80))
ipaddr=(s.getsockname()[0])
print(ipaddr)
#db = pymysql.connect(host='192.168.2.247',
#                       user='xjzx',
#                       password='Af1121113',
#                       db='test',
#                       charset='utf8')
#cursor = db.cursor()
global browser
def init():
    global browser
    browser = webdriver.Firefox()
    url='https://www.2-class.com/'
    browser.get(url)
    browser.maximize_window()
    browser.implicitly_wait(30)
def findxpath(xpath,t=5):
    global browser
    browser.implicitly_wait(t)
    try:
        result = browser.find_element_by_xpath(xpath)
    except :
        logging.info("not find xpath!")
        result= None

    return result

def clickobj(obj):
    global browser
    actions = ActionChains(browser)
    actions.move_to_element(obj)
    actions.click(obj)
    actions.perform()
def _choice():
    title=findxpath('//*[@id="app"]/div/div[1]/div/div/div[1]/div[2]/div[1]/div')
    title=title.get_attribute('innerText')
    d={"A":1,"B":2,"C":3,"D":4}
    #title=title.replace("\n","")
    title=title.replace(" ","")
    title=title.replace("<br/>","")
    title=title.replace('\u3000',"")
    print(title)
    sql= "select questionAnswer from \"main\".\"2_class\" where \"questionTitle\" ='%s'"%(title)
    r=cur.execute(sql)
    t=r.fetchone()
    t=t[0]
    print(t)
    print(t[0])
    c=findxpath("/html/body/div/div/div[1]/div/div/div[1]/div[2]/div[2]/div/label[%d]/span[2]/div"%(d[t[0]]))
    c.click()
    # /html/body/div/div/div[1]/div/div/div[1]/div[2]/div[2]/div/label[1]/span[2]/div
    # /html/body/div/div/div[1]/div/div/div[1]/div[2]/div[2]/div/label[2]/span[2]/div
    # /html/body/div/div/div[1]/div/div/div[1]/div[2]/div[2]/div/label[3]/span[2]/div
def waitElement(xpath,waittime=10):
    global browser
    try:
        WebDriverWait(browser,waittime).until(EC.visibility_of_element_located((By.XPATH,xpath)))
    except:
        return False
    else:
        return True

def login(username="luoping6039",password="78102442"):
    login=findxpath("/html/body/div[1]/div/div[1]/div/div/main/div[1]/div[1]/div/div[2]/div/button")
    clickobj(login)
    account=findxpath('//*[@id="account"]')
    pwd=findxpath('//*[@id="password"]')
    account.send_keys(username)
    pwd.send_keys(password)
    login=findxpath("/html/body/div[2]/div/div[2]/div/div[1]/div/form/div/div/div/button")
    login.click()
    d=findxpath("/html/body/div[2]/div/div[2]/div/div[1]/div/div/div[4]",2)
    if(d!=None):
        clickobj(d)
        time.sleep(1)
def c1():
    time.sleep(3)
    waitElement('//*[@id="app"]/div/div[1]/div/div/main/div[1]/div[1]/div/div[2]/span/a/button')
    qa=findxpath('//*[@id="app"]/div/div[1]/div/header/div/nav/ul/li[8]/a')
    qa.click()

    browser.execute_script('window.scrollTo(0,700)')

    
    f=findxpath("/html/body/div/div/div[1]/div/div/div[1]/div[2]/div[1]/div/div[1]/div[2]/p[1]/span",3)
    if(f != None):return False
    t=findxpath('//*[@id="app"]/div/div[1]/div/div/div[1]/div[2]/div/div[1]/button')
    t.click()
    browser.execute_script('window.scrollTo(0,700)')

    for i in range(19):
        _choice()
        ne=findxpath("//span[text()='下一题']")
        clickobj(ne)
    _choice()
    ne=findxpath("//span[text()='提 交']")
    clickobj(ne)


if __name__ =="__main__":
    while 1:
        r=cur.execute("SELECT * FROM \"userinfo\"  where status is null LIMIT 0, 1")
        # r=cur.execute("SELECT * FROM \"userinfo\"  where status = '0' LIMIT 0, 1")
        r=r.fetchone()
        if(r==None): break
        try:
            cur.execute("UPDATE \"main\".\"userinfo\" SET \"status\"=-1 WHERE (\"id\"=%d)"%(r[0]))
            db.commit()
            init()
            login(r[1],r[2])
            c1()
            f=findxpath("/html/body/div/div/div[1]/div/div/div[1]/div[2]/div[1]/div/div[1]/div[2]/p[1]/span")
            print(f.get_attribute('innerText'))
            cur.execute("UPDATE \"main\".\"userinfo\" SET \"status\"=%d WHERE (\"id\"=%d)"%(int(f.get_attribute('innerText')),r[0]))
            db.commit()
        except:
            
            cur.execute("UPDATE \"main\".\"userinfo\" SET \"status\"=-2 WHERE (\"id\"=%d)"%(r[0]))
            db.commit()

        finally:
            try:
                browser.close()
            except:
                pass


    a=input()
    #https://www.2-class.com/courses/exams/1109